// pages/realTime/realTime.js
import * as echarts from '../../ec-canvas/echarts';
//定义3个websocket链接的全局变量
var _ws1 = null;
var _ws2 = null;
var _ws3 = null;
//定义websock链接的url地址全局变量
var url_basic = null;
var url_production = null;
var url_quality = null;
//图表显示状态的切换标志
var flag_Production=false;
//用于设备映射
var map = {
    '1': 'D81L',
    '2': 'TM19_1',
    '3': 'TM19_2',
    '4': 'TM15'
};
var map_id = {
    '1': 'hl30003016',
    '2': 'HL30003017',
    '3': 'HL30003018',
    '4': 'HL30003019'
};
//定义一个图表全局变量
var chart_production = null;
var chart_bopu=null;
var chart_quality=null;
//定义一个数组用于存放4个生产线的产能数据
var productionData = [];
var leftQualityEcData=[];
var rightQualityEcData=[];
//用于初始化prodution图表的函数
function initProductionChart(canvas, width, height, dpr) {
    chart_production = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
    });
    chart_production.showLoading(); // 首次显示加载动画

    canvas.setChart(chart_production);
    chart_production.setOption(option);
    chart_production.hideLoading(); // 隐藏加载动画
    return chart_production;
}

//波谱图的初始化函数
function initBopuChart(canvas, width, height, dpr) {
    chart_bopu = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
    });
    chart_bopu.showLoading(); // 首次显示加载动画

    canvas.setChart(chart_bopu);
    chart_bopu.setOption(option2);
    chart_bopu.hideLoading(); // 隐藏加载动画
    return chart_bopu;
}
//质量图表数据
function initQualityChart(canvas, width, height, dpr) {
    chart_quality = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
    });
    chart_quality.showLoading(); // 首次显示加载动画

    canvas.setChart(chart_quality);
    chart_quality.setOption(option_quality);
    chart_quality.hideLoading(); // 隐藏加载动画
    return chart_quality;
}


Page({

    /**
     * 页面的初始数据
     */
    data: {
        deviceName: '',
        //设备基本信息
        basicInfo: {
            deliverSpeed: {
                value: "",
                timestamp: ""
            },
            // deviceName: {
            //     value: "HL",
            //     timestamp: ""
            // },
            deviceType: {
                value: "",
                timestamp: ""
            },
            rollerSpeed: {
                value: "",
                timestamp: ""
            },
            total: {
                value: "",
                timestamp: ""
            }
        },
        //左右眼质量数据
        leftAndRightInfo: {
            a_l: {
                value: "",
                timestamp: ""
            },
            a_r: {
                value: "",
                timestamp: ""
            },
            cv1m_l: {
                value: "",
                timestamp: ""
            },
            cv1m_r: {
                value: "",
                timestamp: ""
            },
            cv5m_l: {
                value: "",
                timestamp: ""
            },
            cv5m_r: {
                value: "",
                timestamp: ""
            },
            cv_l: {
                value: "",
                timestamp: ""
            },
            cv_r: {
                value: "",
                timestamp: ""
            },
            d_r: {
                value: "",
                timestamp: ""
            },
            d_l: {
                value: "",
                timestamp: ""
            },
        },
        // 甲乙丙丁产量以及总产量
        production: {
            aShift: {
                value: "",
                timestamp: ""
            },
            bShift: {
                value: "",
                timestamp: ""
            },
            cShift: {
                value: "",
                timestamp: ""
            },
            dShift: {
                value: "",
                timestamp: ""
            },
            total: {
                value: "",
                timestamp: ""
            }
        },
        // index用于拼接url字符串
        index: '',

        //柱状图的初始化函数
        ecLine: {
            onInit: initProductionChart
        },
        //图表显示的标志
        flag_Production:flag_Production,
        //波谱图的初始化函数：
        ecBopu: {
            onInit:initBopuChart
        },
        ecQuality:{
            onInit:initQualityChart
        }

    },

    /* 
    写各种methods
    */
    tapDialogButton(e) {
        // console.log(e);
        if (e.detail.index == 1) {
            console.log("你点击的时确认哦！");
        } else {
            console.log("你点击的是取消哦！");
        }
    },
    //产能信息图表是否显示
    productionEchartChange(){
        this.setData({
            flag_Production:!this.data.flag_Production
        })
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var _this = this;
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('ChildEvent', { data: 'test2' });
        // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
        eventChannel.on('FatherEvent', function(data) {
            console.log(data.index);
            //将上个页面的数据保存到当前页面的data中
            _this.setData({
                index: data.index
            });
            var url_device = map[_this.data.index]
            var device_id = map_id[_this.data.index]
            _this.setData({
                    deviceName: device_id
                })
                //拼接WebSocket url
            url_basic = 'ws://47.106.243.139:8085/api/websocket/basic' + url_device;
            url_production = 'ws://47.106.243.139:8085/api/websocket/production' + url_device;
            url_quality = 'ws://47.106.243.139:8085/api/websocket/quality' + url_device;
            console.log(url_basic);

            //进行WebSocket连接

            var ws1 = wx.connectSocket({ //打开websocket连接
                url: url_basic,
                success: function(resConnect) { //打开连接成功
                    // console.log(resConnect)
                    console.log("ws1连接成功!~");
                },
                fail: function(resConnectError) { //打开连接失败
                    // console.log(resConnectError)
                }
            });
            ws1.onOpen(function(res) {
                if (ws1.readyState === 1) {
                    ws1.send({
                        data: JSON.stringify({
                            number: '123',
                        }),
                        success: function(resSend) {
                            // console.log(resSend)

                        },
                        fail: function(resSendError) {
                            // console.log(resSendError)
                        }
                    })
                }
            });
            ws1.onMessage(function(data) {
                let objData = JSON.parse(data.data);
                const basicInfo = objData;
                //更新basicInfo，使用es6语法
                _this.setData({
                    basicInfo
                });
            });
            _ws1 = ws1;

            //左右眼质量指标对比的websocket链接
            let ws2 = wx.connectSocket({ //打开websocket连接
                //   url: 'ws://47.106.243.139:8085/api/websocket/qualityD81L',
                url: url_quality,
                success: function(resConnect) { //打开连接成功
                    console.log("ws2连接成功!~");
                },
                fail: function(resConnectError) { //打开连接失败
                }
            });
            ws2.onOpen(function(res) {
                if (ws2.readyState === 1) {
                    ws2.send({
                        data: JSON.stringify({
                            number: '123',
                        }),
                        success: function(resSend) {},
                        fail: function(resSendError) {}
                    })
                }
            })
            ws2.onMessage(function(data) {
                let objData = JSON.parse(data.data);
                const leftAndRightInfo = objData;
                //更新basicInfo，使用es6语法
                _this.setData({
                    leftAndRightInfo
                });


                //清空数组
                for(var i=0;i<5;i++){
                    leftQualityEcData.shift();
                    rightQualityEcData.shift();
                }

                //将服务器发过来的数据保存到echarts的渲染图表所需的数组中
                if(JSON.stringify(_this.data.leftAndRightInfo)!='{}'){
                    console.log("进来判断了");
                    console.log(_this.data.leftAndRightInfo);
                    //左眼质量数据
                    leftQualityEcData.push(_this.data.leftAndRightInfo.a_l);
                    leftQualityEcData.push(_this.data.leftAndRightInfo.cv1m_l);
                    leftQualityEcData.push(_this.data.leftAndRightInfo.cv5m_l);
                    leftQualityEcData.push(_this.data.leftAndRightInfo.cv_l);
                    leftQualityEcData.push(_this.data.leftAndRightInfo.d_l);
                    //右眼质量数据
                    rightQualityEcData.push(_this.data.leftAndRightInfo.a_r);
                    rightQualityEcData.push(_this.data.leftAndRightInfo.cv1m_r);
                    rightQualityEcData.push(_this.data.leftAndRightInfo.cv5m_r);
                    rightQualityEcData.push(_this.data.leftAndRightInfo.cv_r);
                    rightQualityEcData.push(_this.data.leftAndRightInfo.d_r);
                }
                //更新表格设置中的data数据
                option_quality.series[0].data=leftQualityEcData;
                option_quality.series[1].data=rightQualityEcData;
                //重新渲染图表
                chart_quality.setOption(option_quality);


            })
            _ws2 = ws2;

            //甲乙丙丁产量对比的websocket链接
            let ws3 = wx.connectSocket({ //打开websocket连接
                //   url: 'ws://47.106.243.139:8085/api/websocket/productionD81L',
                url: url_production,
                success: function(resConnect) { //打开连接成功
                    console.log("ws3连接成功!~");

                },
                fail: function(resConnectError) { //打开连接失败
                }
            });
            ws3.onOpen(function(res) {
                if (ws3.readyState === 1) {
                    ws3.send({
                        data: JSON.stringify({
                            number: '123',
                        }),
                        success: function(resSend) {
                            // console.log(resSend)

                        },
                        fail: function(resSendError) {
                            // console.log(resSendError)
                        }
                    })
                }
            })
            ws3.onMessage(function(data) {
                let objData = JSON.parse(data.data);
                // console.log(objData);
                const production = objData;
                //更新basicInfo，使用es6语法
                _this.setData({
                    production
                });
                //将产能信息存入 productionData数据中用于更新产能信息图表
                productionData.shift();
                productionData.shift();
                productionData.shift();
                productionData.shift();
    
                if(JSON.stringify(_this.data.production) != '{}'){
                    console.log(_this.data.production);
                    productionData.push(_this.data.production.aShift.value);
                    productionData.push(_this.data.production.bShift.value);
                    productionData.push(_this.data.production.cShift.value);
                    productionData.push(_this.data.production.dShift.value);
                }
                //更新表格设置中的data数据
                option.series[0].data=productionData;
                //重新渲染图表
                chart_production.setOption(option);
            })
            _ws3 = ws3;

        });

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        // 小技巧，提前讲this指针存起来，以免和后面的this冲突
        const _this = this;
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        _ws1.close({
            success: function(result) {
                console.log("ws1连接成功关闭");
            }
        });
        _ws2.close({
            success: function(result) {
                console.log("ws2连接成功关闭");
            }
        });
        _ws3.close({
            success: function(result) {
                console.log("ws3连接成功关闭");
            }
        });

        //清空页面数据
        this.setData({
                deviceName: '',
                //设备基本信息
                basicInfo: {},
                // //左右眼质量数据
                leftAndRightInfo: {},
                // 甲乙丙丁产量以及总产量
                production: {},
                // index用于拼接url字符串
                index: ''
            }),
            productionData=[];

            // console.log("OnUpload函数");
            // console.log(this.data.basicInfo);

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})


// for (let i = 0; i < 4; ++i) {
//     productionData.push(Math.round(Math.random() * 200));
// }
var option = {
    title: {
        text: '并条机生产线数据对比',
    },
    grid: {
        width: "75%"
      },
    xAxis: {
        max: 'dataMax',
        splitNumber:3,
    },
    yAxis: {
        type: 'category',
        data: ['甲班', '乙班', '丙班', '丁班', ],
        inverse: true,
        
        animationDuration: 300, //动画持续时间
        animationDurationUpdate: 300, //动画更新持续时间
        max: 4, // only the largest 3 bars will be displayed
       
    },
    series: [{
        realtimeSort: true,
        name: 'X',
        type: 'bar',
        data: productionData,
        label: {
            show: true,
            position: 'right',
            valueAnimation: true
        }
    }],
    legend: {
        show: false,
        left: '60%'
    },
    animationDuration: 0,
    animationDurationUpdate: 3000,
    animationEasing: 'linear',
    animationEasingUpdate: 'linear'
};

//第二张波谱图
var base = +new Date(1988, 9, 3);
var oneDay = 24 * 3600 * 1000;

var data = [[base, Math.random() * 300]];

for (var i = 1; i < 20000; i++) {
    var now = new Date(base += oneDay);
    data.push([
        [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'),
        Math.round((Math.random() - 0.5) * 20 + data[i - 1][1])
    ]);
}

var option2 = {
    tooltip: {
        trigger: 'axis',
        position: function (pt) {
            return [pt[0], '10%'];
        }
    },
    title: {
        left: 'center',
        // text: '波谱图',
    },
    toolbox: {
        feature: {
            dataZoom: {
                yAxisIndex: 'none'
            },
            restore: {},
        }
    },
    xAxis: {
        type: 'time',
        boundaryGap: false
    },
    yAxis: {
        type: 'value',
        boundaryGap: [0, '100%']
    },
    dataZoom: [{
        type: 'inside',
        start: 0,
        end: 20
    }, {
        start: 0,
        end: 20
    }],
    series: [
        {
            name: '模拟数据',
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: {},
            data: data
        }
    ]
};

//质量图表数据设置

var option_quality = {
    title:{
        text:'出口棉条左右眼质量数据对比'
    },
    xAxis: {
        type: 'category',
        data: ['A%', 'CV%1m', 'CV%5m', 'CV%', 'D%']
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        data: leftQualityEcData,
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
            color: 'rgba(220, 220, 220, 0.8)'
        }
    },
    {
        data: rightQualityEcData,
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
            color: 'rgba(220, 220, 220, 0.8)'
        }
    },   
    ]
};